<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import { Head, Link, router } from '@inertiajs/vue3';
import { ref, computed } from 'vue';
import { 
    ArrowUpIcon, 
    StarIcon, 
    ClockIcon, 
    FireIcon, 
    UserGroupIcon, 
    CheckIcon,
    HeartIcon,
    ChatBubbleLeftIcon,
    EyeIcon,
    BuildingOfficeIcon
} from '@heroicons/vue/24/solid';
import { HeartIcon as HeartIconOutline, ChatBubbleLeftIcon as ChatBubbleLeftIconOutline } from '@heroicons/vue/24/outline';

const props = defineProps({
    posts: {
        type: Object,
        required: true,
    },
    popularBars: {
        type: Array,
        default: () => [],
    },
    filters: {
        type: Object,
        default: () => ({
            sort: 'recommended',
            category: 'all',
        }),
    },
    isAuthenticated: {
        type: Boolean,
        default: false,
    },
});

const activeSort = ref(props.filters.sort || (props.isAuthenticated ? 'following' : 'hot'));
const activeCategory = ref(props.filters.category || 'all');

const pageTitle = computed(() => {
    const sortMap = {
        recommended: '推荐内容',
        hot: '热门内容',
        latest: '最新内容',
        following: '关注内容',
    };
    return sortMap[activeSort.value] || '推荐内容';
});

const pageDescription = computed(() => {
    const descMap = {
        recommended: '发现你感兴趣的话题和讨论',
        hot: '浏览当前最热门的帖子',
        latest: '查看最新发布的帖子',
        following: '查看你关注的贴吧最新动态',
    };
    return descMap[activeSort.value] || '发现你感兴趣的话题和讨论';
});

const sortOptions = computed(() => {
    // 已登录用户：关注、推荐、最新、热门
    // 未登录用户：热门、最新
    if (props.isAuthenticated) {
        return [
            { key: 'following', label: '关注', icon: 'users', requiresAuth: true },
            { key: 'recommended', label: '推荐', icon: 'check', requiresAuth: true },
            { key: 'latest', label: '最新', icon: 'clock', requiresAuth: false },
            { key: 'hot', label: '热门', icon: 'trending', requiresAuth: false },
        ];
    }
    return [
        { key: 'hot', label: '热门', icon: 'trending', requiresAuth: false },
        { key: 'latest', label: '最新', icon: 'clock', requiresAuth: false },
    ];
});

const categoryOptions = [
    { key: 'all', label: '全部' },
    { key: 'tech', label: '技术' },
    { key: 'design', label: '设计' },
    { key: 'life', label: '生活' },
    { key: 'entertainment', label: '娱乐' },
];

const handleSort = (sort) => {
    activeSort.value = sort;
    router.get(route('home'), {
        sort,
        category: activeCategory.value,
    }, {
        preserveState: true,
        preserveScroll: true,
    });
};

const handleCategory = (category) => {
    activeCategory.value = category;
    router.get(route('home'), {
        sort: activeSort.value,
        category,
    }, {
        preserveState: true,
        preserveScroll: true,
    });
};

const formatNumber = (num) => {
    if (!num) return '0';
    if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万';
    }
    return num.toString();
};

const formatTime = (time) => {
    if (!time) return '';
    const date = new Date(time);
    const now = new Date();
    const diff = now - date;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    return date.toLocaleDateString('zh-CN');
};

const getUserAvatar = (user) => {
    if (user?.avatar) {
        return user.avatar.startsWith('http') ? user.avatar : `/storage/${user.avatar}`;
    }
    return `https://api.dicebear.com/7.x/avataaars/svg?seed=${user?.name || 'user'}`;
};

const getBarAvatar = (bar) => {
    if (bar?.avatar) {
        return bar.avatar.startsWith('http') ? bar.avatar : `/storage/${bar.avatar}`;
    }
    return `https://api.dicebear.com/7.x/shapes/svg?seed=${bar?.name || 'bar'}`;
};
</script>

<template>
    <Head title="首页" />

    <AuthenticatedLayout>
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- 左侧主要内容区域 -->
            <div class="lg:col-span-2 space-y-6">
                <!-- 帖子流卡片区域 -->
                <div class="bg-white rounded-xl overflow-hidden">
                    <!-- 头部：标题和筛选 -->
                    <div class="px-6 py-6">
                        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                            <div>
                                <h2 class="text-2xl font-bold mb-1.5 text-gray-900">{{ pageTitle }}</h2>
                                <p class="text-sm text-gray-500">{{ pageDescription }}</p>
                            </div>
                        </div>
                    </div>

                    <!-- 标签页导航 -->
                    <div class="px-6 pb-4">
                        <div class="flex flex-col sm:flex-row gap-4">
                            <div class="bg-gray-100 rounded-xl p-1 inline-flex h-10 w-fit">
                                <button
                                    v-for="option in sortOptions"
                                    :key="option.key"
                                    @click="handleSort(option.key)"
                                    :class="[
                                        'inline-flex h-full flex-1 items-center justify-center gap-2 rounded-lg border border-transparent px-4 py-1.5 text-sm font-medium whitespace-nowrap transition-colors',
                                        activeSort === option.key
                                            ? 'bg-white shadow-sm text-gray-900'
                                            : 'text-gray-600 hover:text-gray-900'
                                    ]"
                                    :disabled="option.requiresAuth && !isAuthenticated"
                                >
                                    <CheckIcon v-if="option.icon === 'check'" class="h-4 w-4" />
                                    <FireIcon v-else-if="option.icon === 'trending'" class="h-4 w-4" />
                                    <ClockIcon v-else-if="option.icon === 'clock'" class="h-4 w-4" />
                                    <UserGroupIcon v-else-if="option.icon === 'users'" class="h-4 w-4" />
                                    {{ option.label }}
                                </button>
                            </div>
                            <!-- 分类筛选 -->
                            <div class="flex items-center gap-2 flex-wrap">
                                <span class="text-xs text-gray-600 font-medium">分类：</span>
                                <button
                                    v-for="cat in categoryOptions"
                                    :key="cat.key"
                                    @click="handleCategory(cat.key)"
                                    :class="[
                                        'inline-flex items-center justify-center rounded-lg border px-3 py-1 text-xs font-medium transition-colors',
                                        activeCategory === cat.key
                                            ? 'border-transparent bg-gray-900 text-white shadow-sm'
                                            : 'border-gray-200 bg-white text-gray-700 hover:bg-gray-50'
                                    ]"
                                >
                                    {{ cat.label }}
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- 帖子列表 -->
                    <div class="space-y-0" role="feed" aria-label="帖子列表">
                        <!-- 帖子卡片 -->
                        <article
                            v-for="post in posts.data"
                            :key="post.id"
                            :class="[
                                'post-card group relative px-6 sm:px-8 py-5 sm:py-6 cursor-pointer transition-colors duration-150',
                                post.is_pinned 
                                    ? 'bg-gray-50/30 hover:bg-gray-50/50' 
                                    : post.is_essence
                                        ? 'bg-yellow-50/20 hover:bg-yellow-50/30'
                                        : 'hover:bg-gray-50/30'
                            ]"
                            @click="router.visit(route('posts.show', post.slug))"
                        >
                            <!-- 帖子内容 -->
                            <div class="w-full space-y-2.5">
                                <!-- 第一行：作者 · 贴吧 | 时间 -->
                                <div class="flex items-center justify-between gap-3">
                                    <div class="flex items-center gap-2 flex-wrap min-w-0">
                                        <Link
                                            :href="route('users.show', post.user?.username || post.user?.id)"
                                            class="font-medium text-gray-900 hover:text-gray-700 transition-colors text-sm whitespace-nowrap"
                                            @click.stop
                                        >
                                            {{ post.user?.nickname || post.user?.name }}
                                        </Link>
                                        <span class="text-gray-300 text-xs flex-shrink-0">·</span>
                                        <Link
                                            :href="route('bars.show', post.bar?.slug)"
                                            class="inline-flex items-center gap-1 rounded-lg px-2 py-0.5 text-xs font-medium transition-colors whitespace-nowrap bg-gray-100 text-gray-700 hover:bg-gray-200"
                                            @click.stop
                                        >
                                            <BuildingOfficeIcon class="h-3 w-3 flex-shrink-0" />
                                            <span class="truncate">{{ post.bar?.name }}</span>
                                        </Link>
                                        <span
                                            v-if="post.is_pinned"
                                            class="inline-flex items-center gap-1 rounded-full bg-gray-900 text-white px-2 py-0.5 text-xs font-semibold"
                                        >
                                            <ArrowUpIcon class="h-3 w-3" />
                                            置顶
                                        </span>
                                        <span
                                            v-if="post.is_essence"
                                            class="inline-flex items-center gap-1 rounded-full bg-gradient-to-r from-yellow-400 to-yellow-500 text-white px-2 py-0.5 text-xs font-semibold"
                                        >
                                            <StarIcon class="h-3 w-3" />
                                            精华
                                        </span>
                                    </div>
                                    <span class="text-xs text-gray-400 flex-shrink-0">{{ formatTime(post.created_at) }}</span>
                                </div>

                                <!-- 标题 -->
                                <h3 class="font-bold text-lg sm:text-xl text-gray-900 group-hover:text-gray-700 transition-colors line-clamp-2 leading-tight">
                                    {{ post.title }}
                                </h3>

                                <!-- 内容预览 -->
                                <p class="text-gray-600 line-clamp-2 leading-relaxed text-sm sm:text-base">
                                    {{ post.content }}
                                </p>

                                <!-- 操作栏：点赞、评论（左）| 浏览（右） -->
                                <div class="flex items-center justify-between pt-2">
                                    <div class="flex items-center gap-5">
                                        <button
                                            v-if="isAuthenticated"
                                            class="flex items-center gap-1.5 transition-all group/btn"
                                            :class="post.is_liked ? 'text-gray-900' : 'text-gray-500 hover:text-gray-900'"
                                            @click.stop="router.post(route('posts.like', post.slug || post.id), {}, { preserveState: true, preserveScroll: true })"
                                            aria-label="点赞"
                                        >
                                            <component 
                                                :is="post.is_liked ? HeartIcon : HeartIconOutline" 
                                                class="h-4 w-4 transition-all group-hover/btn:scale-110 group-active/btn:scale-95" 
                                            />
                                            <span class="font-medium text-sm">{{ formatNumber(post.like_count) }}</span>
                                        </button>
                                        <div
                                            v-else
                                            class="flex items-center gap-1.5 text-gray-500"
                                        >
                                            <HeartIconOutline class="h-4 w-4" />
                                            <span class="font-medium text-sm">{{ formatNumber(post.like_count) }}</span>
                                        </div>
                                        <button
                                            class="flex items-center gap-1.5 text-gray-500 hover:text-gray-900 transition-all group/btn"
                                            @click.stop="router.visit(route('posts.show', post.slug))"
                                            aria-label="评论"
                                        >
                                            <ChatBubbleLeftIconOutline class="h-4 w-4 transition-all group-hover/btn:scale-110 group-active/btn:scale-95" />
                                            <span class="font-medium text-sm">{{ formatNumber(post.reply_count) }}</span>
                                        </button>
                                    </div>
                                    <div class="flex items-center gap-1.5 text-gray-400">
                                        <EyeIcon class="h-4 w-4" />
                                        <span class="text-xs">{{ formatNumber(post.views) }} 浏览</span>
                                    </div>
                                </div>
                            </div>
                        </article>

                        <!-- 空状态 -->
                        <div v-if="posts.data.length === 0" class="p-12 text-center text-gray-500">
                            <p class="text-lg mb-2">暂无帖子</p>
                            <p class="text-sm">尝试切换其他排序方式</p>
                        </div>
                    </div>

                    <!-- 分页 -->
                    <div v-if="posts.links && posts.links.length > 3" class="px-6 py-4 border-t border-gray-200">
                        <div class="flex items-center justify-center gap-2">
                            <Link
                                v-for="(link, index) in posts.links"
                                :key="index"
                                :href="link.url || '#'"
                                v-html="link.label"
                                :class="[
                                    'inline-flex items-center justify-center whitespace-nowrap rounded-lg text-sm font-medium transition-all h-9 px-3 py-2',
                                    link.active
                                        ? 'bg-gray-900 text-white shadow-sm'
                                        : link.url
                                            ? 'border border-gray-200 bg-white shadow-sm hover:bg-gray-50 hover:text-gray-900'
                                            : 'text-gray-400 cursor-not-allowed pointer-events-none'
                                ]"
                            />
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧边栏 -->
            <div class="space-y-6">
                <!-- 快速操作卡片 -->
                <div v-if="isAuthenticated" class="bg-white rounded-xl overflow-hidden">
                    <div class="p-6">
                        <h3 class="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                            <svg class="h-5 w-5 text-gray-900" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                            </svg>
                            快速操作
                        </h3>
                        <div class="space-y-3">
                            <Link
                                :href="route('bars.index')"
                                class="flex items-center gap-3 p-4 rounded-xl hover:bg-gray-50 cursor-pointer transition-all border border-gray-200 hover:border-gray-300 hover:shadow-md group"
                            >
                                <div class="w-12 h-12 rounded-xl bg-gradient-to-br from-gray-900/10 to-gray-900/5 flex items-center justify-center flex-shrink-0 group-hover:scale-110 transition-transform">
                                    <svg class="h-6 w-6 text-gray-900" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                                    </svg>
                                </div>
                                <div class="flex-1 min-w-0">
                                    <div class="font-semibold text-sm mb-0.5 text-gray-900">浏览贴吧</div>
                                    <div class="text-xs text-gray-500">发现你感兴趣的社区</div>
                                </div>
                                <svg class="h-4 w-4 text-gray-400 group-hover:text-gray-900 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                                </svg>
                            </Link>
                            <Link
                                :href="route('bars.create')"
                                class="flex items-center gap-3 p-4 rounded-xl hover:bg-gray-50 cursor-pointer transition-all border border-gray-200 hover:border-gray-300 hover:shadow-md group"
                            >
                                <div class="w-12 h-12 rounded-xl bg-gradient-to-br from-gray-900/10 to-gray-900/5 flex items-center justify-center flex-shrink-0 group-hover:scale-110 transition-transform">
                                    <svg class="h-6 w-6 text-gray-900" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                                    </svg>
                                </div>
                                <div class="flex-1 min-w-0">
                                    <div class="font-semibold text-sm mb-0.5 text-gray-900">创建贴吧</div>
                                    <div class="text-xs text-gray-500">创建你的兴趣社区</div>
                                </div>
                                <svg class="h-4 w-4 text-gray-400 group-hover:text-gray-900 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                                </svg>
                            </Link>
                        </div>
                    </div>
                </div>

                <!-- 热门贴吧卡片 -->
                <div v-if="popularBars.length > 0" class="bg-white rounded-xl overflow-hidden">
                    <div class="px-6 py-5">
                        <div class="flex items-center justify-between">
                            <h3 class="text-lg font-bold text-gray-900 flex items-center gap-2">
                                <svg class="h-5 w-5 text-gray-900" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
                                </svg>
                                热门贴吧
                            </h3>
                            <Link
                                :href="route('bars.index')"
                                class="text-sm text-gray-600 hover:text-gray-900 hover:underline font-medium transition-colors"
                            >
                                更多
                            </Link>
                        </div>
                    </div>
                    <div class="px-6 pb-4 space-y-2">
                        <Link
                            v-for="bar in popularBars"
                            :key="bar.id"
                            :href="route('bars.show', bar.slug)"
                            class="flex items-center gap-3 p-3 rounded-xl hover:bg-gray-50 cursor-pointer transition-all group"
                        >
                            <img
                                :src="getBarAvatar(bar)"
                                :alt="bar.name"
                                class="w-12 h-12 rounded-xl flex-shrink-0 border border-gray-200 group-hover:border-gray-300 transition-colors"
                            />
                            <div class="flex-1 min-w-0">
                                <div class="font-semibold text-sm text-gray-900 truncate group-hover:text-gray-700 transition-colors">{{ bar.name }}</div>
                                <div class="text-xs text-gray-500">{{ formatNumber(bar.member_count) }} 成员</div>
                            </div>
                            <svg class="h-4 w-4 text-gray-400 group-hover:text-gray-900 transition-colors opacity-0 group-hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                            </svg>
                        </Link>
                    </div>
                </div>
            </div>
        </div>
    </AuthenticatedLayout>
</template>

<style scoped>
.post-card {
    transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
.post-card:hover {
    transform: translateY(-1px);
}
.post-card:active {
    transform: translateY(0);
}
</style>
